package com.youmingxing.activity.selfInfo;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.youmingxing.AllStarApp;
import com.youmingxing.R;
import com.youmingxing.activity.BaseActivity;
import com.youmingxing.activity.login.PasswordActivity;
import com.youmingxing.activity.login.RegisterByMobileActivity;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.network.AccountApi;
import com.youmingxing.utils.Const;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by JHS on 2015/9/16
 * 帐号设置
 */
public class AccountSettingActivity extends BaseActivity implements View.OnClickListener {


    private RelativeLayout mobleRL;
    private TextView mobileTV;
    private ImageView mobileImage;

    private RelativeLayout changepwRL;

    private RelativeLayout wechatRL;
    private TextView wechatTV;
    private ImageView wechatImage;

    private RelativeLayout microblogRL;
    private TextView microblogTV;
    private ImageView microblogImage;


    private RelativeLayout qqRL;
    private TextView qqTV;
    private ImageView qqImage;


    private Button quitLogin;

    UMSocialService mController;//友盟第三方登陆
    String mobile;
    String qqId;
    String weiboId;
    String weixinId;

    //是否显示修改密码框
    boolean isShowEditPwd = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_acountssetting);
        isShowEditPwd = getIntent().getExtras().getBoolean("is_show_edit_pwd",false);
        initView();
        mController = UMServiceFactory.getUMSocialService("com.umeng.share");
        //设置新浪SSO handler
        mController.getConfig().setSsoHandler(new SinaSsoHandler());
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, Const.APPID_QQ,
                Const.APP_KEY_QQ);
        qqSsoHandler.addToSocialSDK();
        UMWXHandler wxHandler = new UMWXHandler(this, Const.APPID_WEIXIN, Const.SECRET_WEIXIN);
        wxHandler.addToSocialSDK();
        com.umeng.socialize.utils.Log.LOG = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        AccountApi.getbindInfo(jsonHandler);
    }

    private void initView() {
        setTopbarName(R.string.accounts_title);

        mobleRL = (RelativeLayout) findViewById(R.id.moble_rl);
        mobileTV = (TextView) findViewById(R.id.moble_num_tv);
        mobileImage = (ImageView) findViewById(R.id.mobile_icon);

        changepwRL = (RelativeLayout) findViewById(R.id.changepw_rl);

        wechatRL = (RelativeLayout) findViewById(R.id.accounts_wechat_rl);
        wechatTV = (TextView) findViewById(R.id.wechat_num_tv);
        wechatImage  = (ImageView) findViewById(R.id.wechat_icon);

        microblogRL = (RelativeLayout) findViewById(R.id.accounts_microblog_rl);
        microblogTV = (TextView) findViewById(R.id.accounts_microblog_tv);
        microblogImage = (ImageView) findViewById(R.id.microblog_icon);

        qqRL = (RelativeLayout) findViewById(R.id.accounts_qqrl);
        qqTV = (TextView) findViewById(R.id.qq_num_tv);
        qqImage = (ImageView) findViewById(R.id.qq_icon1);
        quitLogin = (Button) findViewById(R.id.quit_login);

        mobleRL.setOnClickListener(this);
        changepwRL.setOnClickListener(this);
        wechatRL.setOnClickListener(this);
        microblogRL.setOnClickListener(this);
        qqRL.setOnClickListener(this);
        quitLogin.setOnClickListener(this);

        if (isShowEditPwd){
            changepwRL.setVisibility(View.VISIBLE);
        } else {
            changepwRL.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.moble_rl:
                if (mobile!=null ){
                    //修改手机号
                    Intent intent = new Intent(AccountSettingActivity.this, RegisterByMobileActivity.class);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                } else {
                    //绑定手机号
                    Intent intent = new Intent(AccountSettingActivity.this, RegisterByMobileActivity.class);
                    intent.putExtra("type", 2);
                    startActivity(intent);
                }
                break;
            case R.id.email_rl:
                showToast("email_rl");
                break;
            case R.id.changepw_rl:
                if (!mobile.isEmpty()) {
                    Intent intent = new Intent(AccountSettingActivity.this, PasswordActivity.class);
                    intent.putExtra("type", 1);
                    intent.putExtra("mobile", mobileTV.getText().toString());
                    startActivity(intent);
                } else {
                    showToast("请先绑定手机");
                }
                break;
            case R.id.accounts_wechat_rl:
                mController.doOauthVerify(this, SHARE_MEDIA.WEIXIN, listener);
                break;
            case R.id.accounts_microblog_rl:
                mController.doOauthVerify(this, SHARE_MEDIA.SINA, listener);
                break;
            case R.id.accounts_qqrl:
                mController.doOauthVerify(this, SHARE_MEDIA.QQ, listener);
                break;

            case R.id.quit_login:
                GlobalDataManager.token = "";
                GlobalDataManager.userInfo = "";
                GlobalDataManager.userId = -1;
                GlobalDataManager.save();
                AllStarApp.closeDaoSession();
//                showToast("已经退出登录");
                finish();
                break;
        }

    }

    JsonHttpResponseHandler jsonHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            if (response.optInt("status") == 200) {
                JSONArray accountArray = response.optJSONArray("data");
                for (int i = 0; i < accountArray.length(); i++) {
                    JSONObject json = accountArray.optJSONObject(i);
                    String content = json.optString("uid");
                    switch (json.optString("provider")) {
                        case "wechat":
                            if (!content.isEmpty()) {
                                wechatTV.setText("已绑定");
                                wechatImage.setImageResource(R.mipmap.have_wechat);
                            }
                            break;
                        case "qq":
                            if (!content.isEmpty()) {
                                qqTV.setText("已绑定");
                                qqImage.setImageResource(R.mipmap.have_qq);
                            }
                            break;
                        case "weibo":
                            if (!content.isEmpty()) {
                                microblogTV.setText("已绑定");
                                microblogImage.setImageResource(R.mipmap.have_weibo);
                            }
                            break;
                        case "mobile":
                            if (!content.isEmpty()) {
                                mobileTV.setText(content);
                                mobile = content;
                                mobileImage.setImageResource(R.mipmap.have_tel);
                            }
                            break;

                    }

                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            //
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    SocializeListeners.UMAuthListener listener = new SocializeListeners.UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(Bundle bundle, final SHARE_MEDIA share_media) {
            final String uid = bundle.getString("uid");
            // 判断是否成功
            if (bundle != null && !TextUtils.isEmpty(uid)) {
                showToast("授权成功");
                //获取用户信息
                mController.getPlatformInfo(AccountSettingActivity.this, share_media, new SocializeListeners.UMDataListener() {
                    @Override
                    public void onStart() {
                        Toast.makeText(AccountSettingActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            if (share_media == SHARE_MEDIA.QQ) {
                                AccountApi.bindOtherAccount("qq", uid, "", othuLoginHandler);
                            } else if (share_media == SHARE_MEDIA.SINA) {
                                AccountApi.bindOtherAccount("weibo", uid, "", othuLoginHandler);
                            } else {
                                //wechat
                                AccountApi.bindOtherAccount("wechat", uid, "", othuLoginHandler);
                            }
                        } else {
                            Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            } else {
                showToast("授权失败");
            }
        }

        @Override
        public void onError(SocializeException e, SHARE_MEDIA share_media) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {

        }
    };

    JsonHttpResponseHandler othuLoginHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            if (response.optInt("status") == 200) {
                switch (response.optJSONObject("data").optInt("result")) {
                    case 0:
                        showToast("系统错误");
                        break;
                    case 1:
                        showToast("绑定成功");
                        AccountApi.getbindInfo(jsonHandler);
                        break;
                    case 2:
                        showToast("该号码已经被其他账号绑定");
                        break;

                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            showToast("绑定失败"+statusCode);
        }
    };

}